import { defineStore } from "pinia";
import { store } from "../index";
import { generateRouter, getFirstMenuUrl } from "@/utils/routerHelper";
import { deepClone } from "@/utils";
import { staticRoutes } from "@/router";
interface Permission {
  routes: any[],
  // 动态添加的路由，需要添加到路由表中的路由
  addRoutes: any[],
  // 默认跳转的路由
  defaultRoutePath: string
  // 是否已经添加动态路由
  isAddRoutes: boolean
}

export const usePermissionStore = defineStore("permission", {
  state: (): Permission => {
    return {
      routes: [],
      addRoutes: [],
      defaultRoutePath: "",
      isAddRoutes: false
    }
  },
  getters: {
    getRoutes(state) {
      return state.routes
    },
    getAddRoutes(state) {
      return state.addRoutes
    },
    getDefaultRoutePath(state) {
      return state.defaultRoutePath
    },
    getIsAddRoutes(state) {
      return state.isAddRoutes
    }
  },
  actions: {
    setRoutes(routes: any) {
      this.routes = routes
    },
    setAddRoutes(routes: any) {
      this.addRoutes = routes
    },
    setIsAddRoutes(isAddRoutes: boolean) {
      this.isAddRoutes = isAddRoutes
    },
    generateRouter(roleRoutes: any) {

      // console.log(roleRoutes);

      return new Promise<void>((resolve) => {
        const routes = generateRouter(deepClone(roleRoutes))

        // console.log(routes);
        

        this.defaultRoutePath = getFirstMenuUrl(roleRoutes)
        this.addRoutes = routes.concat([
          {
            path: '/:path(.*)*',
            redirect: '/404',
            name: '404Page',
            meta: {
              hidden: true,
              breadcrumb: false
            }
          }
        ])
        // console.log(firstMenuUrl);

        let newStaticRoutes = deepClone(staticRoutes)
        this.routes = newStaticRoutes.concat(routes)
        resolve()
      })
    },
  },
  persist: {
    pick: ['routes', 'addRoutes']
  }
})

export const usePermissionStoreWithOut = () => {
  return usePermissionStore(store)
}